package com.cloudsea.yunhaiserver.config;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
        // 直接使用通过 requestFactory() 方法创建的、配置好的工厂实例
        return new RestTemplate(requestFactory);
    }

    @Bean
    public ClientHttpRequestFactory requestFactory() {
        // 1. 创建一个连接池管理器，可以复用连接，提升性能
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(20); // 每个路由的默认最大连接数

        // 2. 创建请求配置，设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(Timeout.ofSeconds(5)) // 从连接池获取连接的超时时间
                .setConnectTimeout(Timeout.ofSeconds(10)) // 建立连接的超时时间
                .setResponseTimeout(Timeout.ofSeconds(10)) // 等待响应的超时时间
                .build();

        // 3. 创建HttpClient实例，应用连接池和请求配置
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                // 【核心】HttpClients.createDefault() 默认就会自动处理GZIP解压，无需额外配置
                .build();

        // 4. 使用HttpClient实例创建Spring的RequestFactory
        return new HttpComponentsClientHttpRequestFactory(httpClient);
    }
}
